$(document).ready(function () {

    var resource = {
        // 封装相关常量
        constant: {
            GET: "GET",
            POST: "POST",
            dataType: "json",
            contentType: "application/json",
            pageSize: 17,
            wholePageNum: 1
        },
        // 封装Role相关ajax的url
        URL: {
            page: function (pageNum, parentId) {
                return $.contextPath() + "/resource/" + pageNum + "/" + resource.constant.pageSize + "?parentId=" + parentId;
            },
            del: function () {
                return $.contextPath() + "/resource/delete";
            },
            find: function (id) {
                return $.contextPath() + "/resource/" + id;
            },
            initTree: function (parentId) {
                return $.contextPath() + "/resource/initResourceTree?parentId=" + parentId;
            }
        },
        // 插件相关设置
        setPluginsInfo: {
            // 设置分页插件总页数
            setTotalPages: function (totalPages) {
                $('#pagination').jqPaginator('option', {
                    totalPages: totalPages
                });
            },
            // 设置分页插件分页信息
            setPageInfo: function (total, pageNum, pageSize) {
                $('#pageInfo').html("共 " + total + " 条数据 当前第 " + pageNum + " 页  每页显示 " + pageSize + " 条");
            },
            // 设置CheckBox样式
            setCheckboxClass: function () {
                $('input[type="checkbox"]').iCheck({
                    checkboxClass: 'icheckbox_square-blue',
                    radioClass: 'iradio_square-blue',
                    increaseArea: '20%'
                });
            },
            // 开启CheckBox全选反选
            openCheckboxSelect: function (checkAllID, checkBoxName) {
                // 全选
                $('#' + checkAllID + '').on('ifChecked', function (event) {
                    $("input[name='" + checkBoxName + "']:checkbox").each(function () {
                        $(this).iCheck('check');
                    });
                });
                // 反选
                $('#' + checkAllID + '').on('ifUnchecked', function (event) {
                    $("input[name='" + checkBoxName + "']:checkbox").each(function () {
                        $(this).iCheck('uncheck');
                    });
                });
            }
        },
        // 工具相关
        util: {
            toJsonString: function (param) {
                return JSON.stringify(param);
            },
            verifyNull: function (param) {
                if (param) {
                    return param;
                } else {
                    return "";
                }
            }
        }
    };


    /*****************************************************权限相关************************************************************************/
    var hasEdit = false;
    var hasDelete = false;
    var permission = {
        verify: {
            auth: function (permission) {
                var param = {'permission': permission};
                $.ajax({
                    async: false,
                    type: resource.constant.POST,
                    url: $.contextPath() + "/admin/hasPermission",
                    dataType: resource.constant.dataType,
                    data: resource.util.toJsonString(param),
                    contentType: resource.constant.contentType,
                    success: function (responseData) {
                        if (responseData) {
                            if (responseData.code == 200) {
                                // 填充数据
                                var datas = responseData.data;
                                if (datas) {
                                    hasEdit = datas[0];
                                    hasDelete = datas[1];
                                }
                            } else {
                                swal("友情提示", responseData.msg);
                            }
                        } else {
                            sweetAlert("异常提示", "返回数据为[null、undefined、NaN]!");
                        }
                    },
                    error: function (data) {
                        sweetAlert("异常提示", "验证权限出现异常，请稍后再试！", "error");
                    }
                });
            }
        }
    };
    // 基于页面调用，判断用户是否有下方执行权限
    verifyHasAdminPermission = function () {
        var permissions = ["resource:edit", "resource:delete"];
        permission.verify.auth(permissions);
    }
    /*****************************************************权限相关************************************************************************/


    /****************************************************分页获取页面数据***************************start*************************************/
    var resourcePage = {
        page: {
            // 分页获取用户列表数据
            getPage: function (pageNum, parentId) {
                $.ajax({
                    type: resource.constant.GET,
                    url: resource.URL.page(pageNum, parentId),
                    dataType: resource.constant.dataType,
                    success: function (responseData) {
                        if (responseData) {
                            if (responseData.code == 200) {
                                var data = responseData.data;
                                // 设置页码信息等
                                resource.setPluginsInfo.setTotalPages(data.pages);
                                // 设置分页信息
                                resource.setPluginsInfo.setPageInfo(data.total, data.pageNum, data.pageSize);
                                // 填充数据
                                resourcePage.page.fullData(data.list);
                                // 设置CheckBox样式
                                resource.setPluginsInfo.setCheckboxClass();
                                // 开启CheckBox全选反选
                                resource.setPluginsInfo.openCheckboxSelect("chkAll", "chkList");
                            } else {
                                // 设置页码信息等
                                resource.setPluginsInfo.setTotalPages(1);
                                // 设置分页信息
                                resource.setPluginsInfo.setPageInfo(0, 1, resource.constant.pageSize);
                                // 填充数据
                                resourcePage.page.fullData(null);
                            }
                        } else {
                            sweetAlert("异常提示", "返回数据为[null、undefined、NaN]!");
                        }
                    },
                    error: function (data) {
                        console.log(data);
                        sweetAlert("异常提示", "获取分页数据出现异常，请稍后再试！", "error");
                    }
                });
            },
            // 填充用户列表数据
            fullData: function (list) {
                var tbody = $('<tbody></tbody>');
                $(list).each(function (index, data) {
                    var tr = $('<tr></tr>');
                    var td = '<td class="t_c"><input type="checkbox" value="' + data.id + '" name="chkList"></td>';
                    td += '<td class="t_c">' + data.id + '</td>';
                    td += '<td class="t_c">' + resource.util.verifyNull(data.text) + '</td>';
                    td += '<td class="t_c">' + resource.util.verifyNull(data.menuType) + '</td>';
                    td += '<td class="t_c">' + resource.util.verifyNull(data.url) + '</td>';
                    td += '<td class="t_c">' + resource.util.verifyNull(data.permission) + '</td>';
                    td += '<td class="t_c">' + resource.util.verifyNull(data.sort) + '</td>';
                    td += '<td class="t_c">' + resource.util.verifyNull(data.icon) + '</td>';
                    td += '<td class="t_c"><div class="visible-md visible-lg hidden-sm hidden-xs action-buttons">';
                    if (hasEdit) {
                        td += '<a class="green" href="#" data-toggle="modal" data-target="#editResource" data-whatever="' + data.id + '"> <i class="icon-pencil bigger-130"></i></a>';
                    }
                    if (hasDelete) {
                        td += '<a class="red" href="#" onclick="deleteData(' + data.id + ')"> <i class="icon-trash bigger-130"></i></a>';
                    }
                    td += '</div></td>';
                    tr.append(td);
                    tbody.append(tr);
                });
                $('#pageInfoData tbody').replaceWith(tbody);
            }
        }
    };
    // 基于页面调用的分页方法
    page = function (pageNum, parentId) {
        resourcePage.page.getPage(pageNum, parentId);
        resource.constant.wholePageNum = pageNum;
    }

    /****************************************************分页获取页面数据***************************end*************************************/


    /****************************************************删除数据***************************start*************************************/

    var resourceDelete = {
        delData: {
            // 验证删除数据是否合法
            verifyDeleteData: function (id) {
                var selectedItems = [];
                if (id) {
                    selectedItems.push(id);
                } else {
                    // 获取checkbox选择的数据项
                    $("input[name='chkList']:checkbox").each(function () {
                        if (true == $(this).is(':checked')) {
                            selectedItems.push($(this).val());
                        }
                    });
                }
                if (null == selectedItems || selectedItems.length < 1) {
                    swal({
                        title: "友情提示",
                        text: "请选择您要删除的数据，可以批量删除 ！",
                        timer: 2000
                    });
                    return;
                }
                return selectedItems;
            },
            // 确实删除方法
            submitDeleteData: function (items) {
                swal({
                        title: "确认删除?",
                        text: "删除数据不可恢复，请谨慎操作！",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "Yes, delete it!",
                        closeOnConfirm: false
                    },
                    function () {
                        resourceDelete.delData.executeDeleteData(items);
                    });
            },
            // 执行删除方法
            executeDeleteData: function (items) {
                var param = {'ids': items};
                $.ajax({
                    type: resource.constant.POST,
                    url: resource.URL.del(),
                    dataType: resource.constant.dataType,
                    data: resource.util.toJsonString(param),
                    contentType: resource.constant.contentType,
                    success: function (responseData) {
                        if (responseData) {
                            if (responseData.code == 200) {
                                page(resource.constant.wholePageNum, $("#page_parentId").val());
                                swal("友情提示", "数据删除成功!", "success");
                                resourceTree.tree.refreshTree(0); // 刷新左侧资源树
                            } else {
                                swal("友情提示", responseData.msg);
                            }
                        } else {
                            sweetAlert("异常提示", "返回数据为[null、undefined、NaN]!");
                        }
                    },
                    error: function (data) {
                        sweetAlert("异常提示", "删除数据出现异常，请稍后再试！", "error");
                    }
                });
            }
        }
    };
    // 基于页面调用的删除方法
    deleteData = function (id) {
        var items = resourceDelete.delData.verifyDeleteData(id);
        if (items) {
            resourceDelete.delData.submitDeleteData(items)
        }
    }
    /****************************************************删除数据***************************end*************************************/


    /****************************************************新增数据***************************start*************************************/
        // 新增弹出层后事件
    $('#addResource').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // 触发事件的按钮
    });
    // 提交新增表单数据
    $('#addResourceForm').on("submit", function () {
        $(this).find("*").each(function(){
            var elem = $(this);
            if (elem.prop("name") != null&&elem.prop("name") != "") {
                if(elem.val()==""){
                    elem.removeAttr("name");
                }
            }
        });
        $(this).ajaxSubmit(
            {
                dataType: "json",
                clearForm: true,
                //提交成功后的回调函数
                success: function (data, status, xhr, $form) {
                    console.log("success", data, status, xhr, $form);
                    if (status == 'success' && data.code == 200) {
                        swal("友情提示", "数据添加成功!", "success");
                        $('#addResource').modal('hide');// 隐藏弹出层
                        resourceTree.tree.refreshTree(0);
                        page(1, $("#page_parentId").val());
                    }
                },
                // 提交错误后的回调函数
                error: function (xhr, status, error, $form) {
                    sweetAlert("异常提示", "添加数据出现异常，请稍后再试！", "error");
                }
            }
        );
        return false; //阻止表单默认提交
    });
    /****************************************************新增数据***************************end*************************************/


    /****************************************************修改数据***************************start*************************************/
    var resourceEdit = {
        find: {
            // 查询当前修改对象
            findResource: function (id) {
                $.ajax({
                    type: resource.constant.GET,
                    url: resource.URL.find(id),
                    dataType: resource.constant.dataType,
                    success: function (responseData) {
                        if (responseData) {
                            if (responseData.code == 200) {
                                // 填充数据
                                resourceEdit.find.fullEditData(responseData.data);
                            } else {
                                swal("友情提示", responseData.msg);
                            }
                        } else {
                            sweetAlert("异常提示", "返回数据为[null、undefined、NaN]!");
                        }
                    },
                    error: function (data) {
                        console.log(data);
                        sweetAlert("异常提示", "获取当前修改对象出现异常，请稍后再试！", "error");
                    }
                });
            },
            // 填充修改表单数据
            fullEditData: function (data) {
                $("#edit_id").val(data.id);
                $("#edit_text").val(data.text);
                $("#edit_menuType").val(data.menuType);
                $("#edit_aliases").val(data.aliases);
                $("#edit_url").val(data.url);
                $("#edit_permission").val(data.permission);
                $("#edit_sort").val(data.sort);
                $("#edit_icon").val(data.icon);
                $("#edit_module").val(data.module);
            }
        }
    };
    // 修改弹出层后事件
    $('#editResource').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // 触发事件的按钮
        var id = button.data('whatever'); // 解析出data-whatever内容，用来传输数据
        resourceEdit.find.findResource(id);//获得的数据
    });
    // 提交修改表单数据
    $('#editResourceForm').on("submit", function () {
        $(this).find("*").each(function(){
            var elem = $(this);
            if (elem.prop("name") != null&&elem.prop("name") != "") {
                if(elem.val()==""){
                    elem.removeAttr("name");
                }
            }
        });
        $(this).ajaxSubmit(
            {
                dataType: "json",
                clearForm: true,
                //提交成功后的回调函数
                success: function (data, status, xhr, $form) {
                    console.log("success", data, status, xhr, $form);
                    if (status == 'success' && data.code == 200) {
                        swal("友情提示", "数据修改成功!", "success");
                        $('#editResource').modal('hide');// 隐藏弹出层
                        page(1, $("#page_parentId").val());
                        resourceTree.tree.refreshTree(0);
                    }
                },
                // 提交错误后的回调函数
                error: function (xhr, status, error, $form) {
                    sweetAlert("异常提示", "修改当前数据出现异常，请稍后再试！", "error");
                }
            }
        );
        return false; //阻止表单默认提交
    });
    /****************************************************修改数据***************************end*************************************/

    var selectIconAction;
    $('#openSelsectIcon').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // 触发事件的按钮
        selectIconAction = button.data('whatever'); // 解析出data-whatever内容，用来传输数据
    });

    selectIcon = function (icon) {
        if(selectIconAction == "edit"){
            $("#edit_icon_text").val(icon);
            $("#edit_icon").addClass(icon);
        }else{
            $("#add_icon_text").val(icon);
            $("#add_icon").addClass(icon);
        }
        $('#openSelsectIcon').modal('hide');// 隐藏弹出层
    }

    /****************************************************资源树***************************start*************************************/
    var resourceTree = {
        tree: {
            // 初始化资源树
            initResourceTree: function (parentId) {
                $.ajax({
                    type: resource.constant.GET,
                    url: resource.URL.initTree(parentId),
                    dataType: resource.constant.dataType,
                    success: function (responseData) {
                        if (responseData) {
                            if (responseData.code == 200) {
                                // 初始化资源树
                                resourceTree.tree.createResourceTree(responseData.data);
                            } else {
                                sweetAlert("友情提示", responseData.msg);
                            }
                        } else {
                            sweetAlert("异常提示", "返回数据为[null、undefined、NaN]!");
                        }
                    },
                    error: function (data) {
                        console.log(data);
                        sweetAlert("异常提示", "获取当前修改对象出现异常，请稍后再试！", "error");
                    }
                });
            },
            // 构建资源树
            createResourceTree: function (data) {
                $('#resourceTree').jstree({
                    'core': {
                        "animation": 0,
                        "check_callback": true,
                        'force_text': true,
                        'data': data,
                    },
                    'plugins': ["wholerow", "types", "search", 'dnd', '"state"']
                }).on("select_node.jstree", function (obj, node) {// 资源树选择事件
                    var parentId = node.node.id;
                    var parentText = node.node.text;
                    $("#page_parentId").val(parentId);
                    $("#add_parent_id").val(parentId);
                    $("#add_parent_text").val(parentText);
                    page(1, parentId);
                });
            },
            // 刷新资源树
            refreshTree: function (parentId) {
                var resourceTree = $('#resourceTree').jstree(true);
                $.ajax({
                    type: resource.constant.GET,
                    url: resource.URL.initTree(parentId),
                    dataType: resource.constant.dataType,
                    success: function (responseData) {
                        if (responseData) {
                            if (responseData.code == 200) {
                                // 初始化资源树
                                resourceTree.settings.core.data = responseData.data;
                                resourceTree.refresh(true);
                            } else {
                                alert(responseData.msg);
                            }
                        } else {
                            sweetAlert("异常提示", "返回数据为[null、undefined、NaN]!");
                        }
                    },
                    error: function (data) {
                        console.log(data);
                        sweetAlert("异常提示", "获取当前修改对象出现异常，请稍后再试！", "error");
                    }
                });
            }
        }
    };

    // 初始化资源树
    initResourceTree = function(){
        resourceTree.tree.initResourceTree(0);
    };
    /****************************************************资源树***************************end*************************************/

});

